package com.psct.ui;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ViewSwitcher.ViewFactory;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.actionbarsherlock.view.Window;
import com.actionbarsherlock.widget.SearchView;
import com.actionbarsherlock.widget.SearchView.OnQueryTextListener;
import com.psct.Constant;
import com.psct.R;
import com.psct.ThreadPool;
import com.psct.adapter.GalleryAdapter;
import com.psct.bean.TextData;
import com.psct.data.PSCTDatabase;
import com.psct.data.PSCTSettingSave;
import com.psct.music.MusicManager;
import com.psct.wiget.SearchListView;
import com.psct.wiget.SearchListView.SearchAdapter;

public class MainActivity extends SherlockFragmentActivity implements OnQueryTextListener,
		OnItemClickListener, OnClickListener, OnFocusChangeListener, ViewFactory,
		OnItemSelectedListener {
	public static final String TAG = "main";
	private SearchView searchView;
	private Gallery gallery;
	private ImageSwitcher switcher;
	private Integer[] mImageIds = {
			// 定义整型数组 即图片源
			R.drawable.yy01_001, R.drawable.yy02_001, R.drawable.yy03_001, R.drawable.yy04_001,
			R.drawable.yy05_001, R.drawable.yy06_001, R.drawable.yy07_001, R.drawable.yy08_001,
			R.drawable.yy09_001, R.drawable.yy10_001, R.drawable.yy11_001, R.drawable.yy12_001, };

	private Handler handler = new Handler() {
	};
	/**
	 * 当前课本的坐标
	 */
	protected int curIndex;
	private List<TextData> textList;
	private SearchListView sList;
	private ListView sListView;
	private SearchAdapter sAdapter;
	ActionBar actionBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY);
		actionBar = this.getSupportActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.actionbar_bg));
		setContentView(R.layout.activity_main);
		MusicManager.getInstance().setContext(getApplicationContext());
		initUI();
		handBgMusic();
	}

	/**
	 * 处理背景音乐
	 */
	private void handBgMusic() {
		if (new PSCTSettingSave(this).isMusicAutoPlay()) {
			final int mode = new PSCTSettingSave(getApplicationContext()).getPlayModel();
			handler.postDelayed(new Runnable() {
				public void run() {
					MusicManager.getInstance().setMode(mode);
				}
			}, 5000);
		}
	}

	/**
	 * 初始化UI
	 */
	protected void initUI() {
		gallery = (Gallery) this.findViewById(R.id.gallery);
		switcher = (ImageSwitcher) this.findViewById(R.id.switcher);
		switcher.setFactory(this);
		switcher.setInAnimation(this, android.R.anim.fade_in);
		switcher.setOutAnimation(this, android.R.anim.fade_out);
		switcher.setOnClickListener(this);
		gallery.setAdapter(new GalleryAdapter(this));
		gallery.setOnItemSelectedListener(this);
		gallery.setSelection(Integer.MAX_VALUE / 2);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// 添加搜索按钮
//		searchView = new SearchView(getSupportActionBar().getThemedContext());
//		searchView.setQueryHint("输入课文标题");
//		searchView.setOnQueryTextListener(this);
//		searchView.setOnQueryTextFocusChangeListener(this);
//		menu.add("搜索")
//				.setIcon(R.drawable.abs__ic_search_api_holo_light)
//				.setActionView(searchView)
//				.setShowAsAction(
//						MenuItem.SHOW_AS_ACTION_IF_ROOM
//								| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);

		// 添加更多菜单
		SubMenu sub = menu.addSubMenu("更多")
				.setIcon(R.drawable.abs__ic_menu_moreoverflow_holo_light);
		sub.add(0, Constant.MENU_PERSONAL, 0, "个人中心");
		sub.add(0, Constant.MENU_UPLOAD, 0, "更新数据");
		sub.add(0, Constant.MENU_SETTING, 0, "系统设置");
		sub.add(0, Constant.MENU_ABOUTUS, 0, "关于我们");
		sub.getItem().setShowAsAction(
				MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case Constant.MENU_ABOUTUS:// 关于我们

			break;

		case Constant.MENU_PERSONAL:// 个人中心
			Intent intent2 = new Intent(this, PersonalActivity.class);
			this.startActivity(intent2);
			break;

		case Constant.MENU_SETTING:// 设置
			Intent intent = new Intent(this, SettingActivity.class);
			this.startActivity(intent);
			break;

		case Constant.MENU_UPLOAD:// 更新数据

			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		// TODO 查询提交的时候调用
		Log.v(TAG, "onQueryTextSubmit:" + query);
		return false;
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		// TODO 查询文字改变的时候调用
		Log.v(TAG, "onQueryTextChange:" + newText);
		if (sAdapter != null) {
			sAdapter.getFilter().filter(newText);
		}
		return true;
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		// TODO Auto-generated method stub
		Log.v("search", "查询焦点：" + hasFocus);
		Log.v(TAG, "宽度:" + searchView.getChildAt(0).getWidth());
		if (hasFocus) {
			if (textList == null) {
				ThreadPool.execute(new Runnable() {

					@Override
					public void run() {
						textList = new PSCTDatabase(MainActivity.this).querryTextAll();
						MainActivity.this.runOnUiThread(new Runnable() {

							@Override
							public void run() {
								if (sList == null) {
									sList = new SearchListView(MainActivity.this, searchView
											.getWidth());
									sListView = sList.getListView();
									sListView.setOnItemClickListener(MainActivity.this);
									sAdapter = (SearchAdapter) sListView.getAdapter();
									sAdapter.setData(textList);
								}
								sList.show(searchView);
							}

						});
					}

				});

			} else {
				sList.show(searchView);
			}
		} else {
			sList.dismiss();
		}

	}

	@Override
	public View makeView() {
		ImageView i = new ImageView(this);
		// 给ImageView设置资源
		WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		// 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半
		// int xPos =
		int imageSize = windowManager.getDefaultDisplay().getHeight() / 2;
		i.setLayoutParams(new ImageSwitcher.LayoutParams(imageSize, imageSize));
		return i;
	}

	@Override
	public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
		curIndex = position % mImageIds.length;
		switcher.setImageResource(mImageIds[curIndex]);
	}

	@Override
	public void onNothingSelected(AdapterView<?> parent) {

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Animation bookAnim = AnimationUtils.loadAnimation(this, R.anim.anim_book_open);
		bookAnim.setFillAfter(true);
		handler.postDelayed(new Runnable() {
			public void run() {
				Intent startIntent = new Intent(MainActivity.this, BookListActivity.class);
				startIntent.putExtra("num", curIndex);
				MainActivity.this.startActivity(startIntent);
				overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
			}
		}, 200);
		switcher.startAnimation(bookAnim);
	}

	@Override
	protected void onDestroy() {
		MusicManager.getInstance().stop();
		super.onDestroy();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(this, TextShowActivity.class);
		intent.putExtra("textId", textList.get(position).getId());
		intent.putExtra("textTitle", textList.get(position).getTitle());
		this.startActivity(intent);
	}

}
